// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.departures

import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import xyz.apiote.bimba.czwek.api.Error
import xyz.apiote.bimba.czwek.api.mapHttpError
import xyz.apiote.bimba.czwek.repo.OnlineRepository
import xyz.apiote.bimba.czwek.repo.StopDepartures
import xyz.apiote.bimba.czwek.repo.TrafficResponseException

class DeparturesViewModel: ViewModel() {
	private val _departures = MutableLiveData<StopDepartures>()
	val departures: LiveData<StopDepartures> = _departures
	private val _error = MutableLiveData<Error>()
	val error: LiveData<Error> = _error
	var requestedItemsNumber = 12
	var allItemsRequested = false

	fun getDepartures(context: Context, feedID: String, code: String, line: String?) {
		MainScope().launch {
			try {
				val repository = OnlineRepository()
				val stopDepartures =
					repository.getDepartures(
						feedID,
						code,
						line,
						context,
						requestedItemsNumber
					)
				stopDepartures?.let {
					if (stopDepartures.departures.isEmpty()) {
						val (string, image) = mapHttpError(404)
						throw TrafficResponseException(404, "", Error(404, string, image))
					}
					_departures.value = it
				}
			} catch (e: TrafficResponseException) {
				if (!departures.isInitialized) {
					_error.value = e.error
				}
				Log.w("Departures", "$e")
			}
		}
	}
}
